/**
* 获取掘金热门沸点
 */
const puppeteer = require('puppeteer');
const url = 'https://juejin.cn/pins/hot';
module.exports = async () => {
    // 打开浏览器
    const browser = await puppeteer.launch({
        args: ['--no-sandbox'],
        headless: 'new'
    });
    // 创建tab标签页
    const page = await browser.newPage();
    // 地址栏输入网址
    await page.goto(url, {
        waitUntil: 'networkidle2', // 等待网络状态为空闲的时候才继续执行
    });
    // 等待网页元素加载完成
    await timeout();
    let result = await page.evaluate(() => {
        let result = [];
        const pinListItem = document.querySelectorAll('.pin-list-view .pin-list .item.shadow');
        for (let i = 0; i < pinListItem.length; i++) {
            const item = pinListItem[i];
            const avatar = item.querySelector('.jj-avatar.avatar img').getAttribute('src');
            const username = item.querySelector('.username').innerText;
            const position = item.querySelector('.position').innerText;
            const timeTxt = item.querySelector('.time').innerText;
            const publishTime = item.querySelector('.time').getAttribute('title');
            const content = item.querySelector('.content').innerHTML;
            const diggCount = item.querySelector('.digg-count') ? item.querySelector('.digg-count').innerText : '';
            const description = item.querySelector('.desc') ? item.querySelector('.desc').innerText : '';
            const clubName = item.querySelector('.club') ? item.querySelector('.club span').innerText : '';
            const clubUrl = item.querySelector('.club') ? item.querySelector('.club').getAttribute('href') : '';
            const contentImgList = item.querySelectorAll('.pin-image-row .pin-img');
            const imgArr = [];
            if (contentImgList.length > 0) {
                for (let j = 0; j < contentImgList.length; j++) {
                    const img = contentImgList[j].querySelector('img');
                    imgArr.push(img.getAttribute('src'));
                }
            }
            result.push({
                avatar,
                username,
                position,
                timeTxt,
                publishTime,
                content,
                contentImgList: imgArr,
                hotComment: {
                    diggCount,
                    description
                },
                club: {
                    name: clubName,
                    url: clubUrl ? 'https://juejin.cn' + clubUrl : ''
                }
            });
        }
        // 返回爬取到的数据
        return result;
    });
    // 关闭浏览器
    await browser.close();
    return result;
}

function timeout() {
    return new Promise(resolve => setTimeout(resolve, 2000))
}
